package com.chen.authority.common.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.chen.authority.entity.ColumnEntity;
import com.chen.authority.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 *
 * @author chengy
 */
public class GenUtil {

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<>();
        templates.add("template/Dto.java.vm");
        templates.add("template/Qo.java.vm");
        templates.add("template/Vo.java.vm");
        templates.add("template/Po.java.vm");
        templates.add("template/Mapper.java.vm");
        templates.add("template/api.js.vm");
        templates.add("template/Service.java.vm");
        templates.add("template/ServiceImpl.java.vm");
        templates.add("template/Controller.java.vm");
        templates.add("template/index.vue.vm");
        templates.add("template/sql.vm");
        templates.add("template/Mapper.xml.vm");
        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns, ZipOutputStream zip) {
        //配置信息
        Configuration config = getConfig();
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setName(table.get("name"));
        tableEntity.setDescription(table.get("description"));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getName(), config.getString("tablePrefix"));
        tableEntity.setClassName(className);

        //列信息
        List<ColumnEntity> columnsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setName(column.get("name"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setDescription(column.get("description"));
            columnEntity.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getName());
            columnEntity.setAttrName(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType");
            columnEntity.setAttrType(attrType);

            columnsList.add(columnEntity);
        }
        tableEntity.setColumns(columnsList);

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getName());
        map.put("comments", tableEntity.getDescription());
        map.put("className", tableEntity.getClassName());
        map.put("classname", StrUtil.lowerFirst(tableEntity.getClassName()));
        map.put("pathName", tableEntity.getClassName().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("author", config.getString("author"));
        map.put("datetime", DateUtil.now());
        map.put("date", DateUtil.today());

        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), config.getString("package"), config.getString("moduleName"))));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException("渲染模板失败，表名：" + tableEntity.getName(), e);
            }
        }
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.startsWith(tablePrefix) ? tableName.replaceFirst(tablePrefix, "") : tableName;
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + File.separator + File.separator;
        }

        if (template.contains("Po.java.vm")) {
            return packagePath + "po" + File.separator + className + "Po.java";
        }

        if (template.contains("Vo.java.vm")) {
            return packagePath + "vo" + File.separator + className + "Vo.java";
        }

        if (template.contains("Mapper.java.vm")) {
            return packagePath + "mapper" + File.separator + className + "Mapper.java";
        }

        if (template.contains("Service.java.vm")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.vm")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.vm")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains("Mapper.xml.vm")) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + File.separator + className + "Mapper.xml";
        }

        if (template.contains("Dto.java.vm")) {
            return packagePath + "dto" + File.separator + className + "Dto.java";
        }

        if (template.contains("Qo.java.vm")) {
            return packagePath + "qo" + File.separator + className + "Qo.java";
        }

        if (template.contains("index.vue.vm")) {
            return "views" + File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + "index.vue";
        }

        if (template.contains("sql.vm")) {
            return className.toLowerCase() + ".sql";
        }

        if (template.contains("api.js.vm")) {
            return "api" + File.separator + moduleName + File.separator + className.toLowerCase() + ".js ";
        }

        return null;
    }
}
